package com.googlecode.intellimars.translator;

import com.bitbakery.plugin.translator.Language;
import com.bitbakery.plugin.translator.TranslatorConfig;
import com.google.api.translate.Translate;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.*;

public class TranslatorPanel {
    public JPanel rootPanel;
    private JButton translateButton;
    private JButton reverseTranslateButton;
    private JComboBox fromLang;
    private JComboBox toLang;
    private JTextArea fromTextArea;
    private JTextArea toTextArea;

    public TranslatorPanel() {
        translateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                translate(fromTextArea, fromLang, toTextArea, toLang);
            }
        });
        reverseTranslateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                translate(toTextArea, toLang, fromTextArea, fromLang);
            }
        });
        fromLang.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                hydrateTargetLanguages();
            }
        });
    }

    public void init(TranslatorConfig data) {
        for (Language source : Language.SOURCE_LANGUAGES) {
            fromLang.addItem(source);
            toLang.addItem(source);
        }

        fromLang.setSelectedItem(Language.get(data.getSourceLanguageCode()));

        hydrateTargetLanguages();
        Language language = Language.get(data.getTargetLanguageCode());
        if (language != null) {
            toLang.setSelectedItem(language);
        } else {
            toLang.setSelectedIndex(0);
        }
    }

    private void hydrateTargetLanguages() {
        toLang.removeAllItems();
        Language source = (Language) fromLang.getSelectedItem();
        for (Language target : Language.getTargetLanguages(source)) {
            toLang.addItem(target);
        }
    }

    private String getCode(JComboBox languageComboBox) {
        return languageComboBox.getSelectedItem() == null ? null : ((Language) languageComboBox.getSelectedItem()).code;
    }

    private void translate(JTextArea fromText, JComboBox fromCombo, JTextArea toText, JComboBox toCombo) {
        String text = fromText.getText();
        String source = getCode(fromCombo);
        String target = getCode(toCombo);

        try {
            String translatedText = Translate.translate(text, source, target);
            toText.setText(translatedText);
            toText.setBackground(Color.WHITE);
        }
        catch (Exception e) {
            toText.setText(e.getMessage());
            toText.setBackground(new Color(0xFF, 0xDD, 0xDD));
        }
    }
}
